//
//  PGArticleManager.m
//  PhotographicGuide
//
//  Created by indream on 13-2-23.
//  Copyright (c) 2013年 indream. All rights reserved.
//

#import "PGArticleManager.h"
#import "SBJson/SBJson.h"
#import "PGArticle.h"
#import "PGFavor.h"
#import "PGCoreDataManager.h"
static PGArticleManager*_instance;
static NSString* NOTIFICATION_DATA_LOADED = @"__NOTIFICATION_DATA_LOADED__";
static NSString* NOTIFICATION_VIEWS_LOADED = @"__NOTIFICATION_VIEWS_LOADED__";
static NSString* NOTIFICATION_FAVORS_LOADED = @"__NOTIFICATION_FAVORS_LOADED__";
static NSString* NOTIFICATION_TABLE_REFRESH = @"__NOTIFICATION_TABLE_REFRESH__";
static NSInteger PAGE_COUNT = 4;
static NSString*listURL = @"http://1.starrynightwalk.sinaapp.com/mobile/ios/app_list.php";
static NSString*viewsURL = @"http://1.starrynightwalk.sinaapp.com/mobile/ios/app_views.php";
static NSString*favorsURL = @"http://1.starrynightwalk.sinaapp.com/mobile/ios/app_favors.php";
@implementation PGArticleManager

-(id)init{
    self = [super init];
    if(self){
        _isDownload = NO;
        _isEndArticle = NO;
        _lastArticleTime = (int)[[NSDate date]timeIntervalSince1970];
        
        self.queue = [[NSOperationQueue alloc]init];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dataLoaded:) name:NOTIFICATION_DATA_LOADED object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(viewsDataLoaded:) name:NOTIFICATION_VIEWS_LOADED object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(favorsDataLoaded:) name:NOTIFICATION_FAVORS_LOADED object:nil];
        
    }
    return self;
}
#pragma mark - public
-(void)addQperator:(PGHttpOperator*)operator{
    [_queue addOperation:operator];
}
-(void)updateLastestArticles{
    _isDownload = YES;
    NSTimeInterval timeInterval = [[NSDate date]timeIntervalSince1970];
    [self addQperator:[[PGHttpOperator alloc]initWithURLString:[listURL stringByAppendingString:
                                                                [NSString stringWithFormat:@"?isdebug=0&count=%d&time=%d&id=0",PAGE_COUNT,(int)timeInterval]] cache:NO notification:NOTIFICATION_DATA_LOADED]];
}
-(void)updateOlderArticles{
    _isDownload = YES;
    [self addQperator:[[PGHttpOperator alloc]initWithURLString:[listURL stringByAppendingString:
                                                                [NSString stringWithFormat:@"?isdebug=0&count=%d&time=%d&id=%d",PAGE_COUNT,_lastArticleTime,_lastArticleId]] cache:NO notification:NOTIFICATION_DATA_LOADED]];
}
-(void)addArticleView:(int)articleId{
    
    [self addQperator:[[PGHttpOperator alloc]initWithURLString:[viewsURL stringByAppendingString:
                                                                [NSString stringWithFormat:@"?action=add&id=%d",articleId]] cache:NO notification:NOTIFICATION_VIEWS_LOADED]];
}
-(void)addArticleFavor:(int)articleId{
    
    [self addQperator:[[PGHttpOperator alloc]initWithURLString:[favorsURL stringByAppendingString:
                                                                [NSString stringWithFormat:@"?action=add&id=%d",articleId]] cache:NO notification:NOTIFICATION_FAVORS_LOADED]];
}
#pragma mark - private
-(void)dataLoaded:(NSNotification*)notification{
    _isDownload = NO;
    NSString*jsonData = [[NSString alloc]initWithData:[notification.userInfo objectForKey:@"data"] encoding:NSUTF8StringEncoding];
    SBJsonParser *parser = [[SBJsonParser alloc]init];
    NSDictionary*json = [parser objectWithString:jsonData];
    if([[json objectForKey:@"code"]intValue]==0){
        NSArray*list = [json objectForKey:@"list"];
        int count = list.count;
        for (int i=0; i<count; i++) {
            [self addArticle:[list objectAtIndex:i]];
        }
    }
    [[PGCoreDataManager sharedInstance]save];
    if(_list.count==0){
        self.list = [[PGCoreDataManager sharedInstance]dataWithPredicateString:[NSString stringWithFormat:@"time between {0, %d} and media == 0", (int)[[NSDate date] timeIntervalSince1970]] entityName:@"Article" fetchLimit:PAGE_COUNT];
    }else{
        int limit = self.list.count+PAGE_COUNT;
        self.list = [[PGCoreDataManager sharedInstance]dataWithPredicateString:[NSString stringWithFormat:@"time between {%d, %d} and media == 0", 0,(int)[[NSDate date] timeIntervalSince1970]] entityName:@"Article" fetchLimit:limit];
    }
    _isEndArticle = _lastArticleTime <= 1330356600;
    [[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATION_TABLE_REFRESH object:nil userInfo:nil];
}
-(void)viewsDataLoaded:(NSNotification*)notification{
    NSString*jsonData = [[NSString alloc]initWithData:[notification.userInfo objectForKey:@"data"] encoding:NSUTF8StringEncoding];
    SBJsonParser *parser = [[SBJsonParser alloc]init];
    NSDictionary*json = [parser objectWithString:jsonData];
    if([[json objectForKey:@"code"]intValue]==0){
        PGArticle*article = [self articleWithID:[[json objectForKey:@"id"]intValue]];
        article.views = [NSNumber numberWithInt:[[json objectForKey:@"count"]intValue]];
        [[PGCoreDataManager sharedInstance]save];
    }
}
-(void)favorsDataLoaded:(NSNotification*)notification{
    NSString*jsonData = [[NSString alloc]initWithData:[notification.userInfo objectForKey:@"data"] encoding:NSUTF8StringEncoding];
    SBJsonParser *parser = [[SBJsonParser alloc]init];
    NSDictionary*json = [parser objectWithString:jsonData];
    if([[json objectForKey:@"code"]intValue]==0){
        PGArticle*article = [self articleWithID:[[json objectForKey:@"id"]intValue]];
        article.favors = [NSNumber numberWithInt:[[json objectForKey:@"count"]intValue]];
        [[PGCoreDataManager sharedInstance]save];
    }
}
-(void)addArticle:(NSDictionary*)dict{
    NSNumber *articleId = [NSNumber numberWithInt:[[dict objectForKey:@"id"]intValue]];
    NSNumber *media = [NSNumber numberWithInt:[[dict objectForKey:@"media"]intValue]];
    NSNumber *time = [NSNumber numberWithInt:[[dict objectForKey:@"time"]intValue]];
    NSNumber *ispub = [NSNumber numberWithInt:[[dict objectForKey:@"ispub"]intValue]];
    NSNumber *views = [NSNumber numberWithInt:[[dict objectForKey:@"views"]intValue]];
    NSNumber *favors = [NSNumber numberWithInt:[[dict objectForKey:@"favors"]intValue]];
    NSString *name = [dict objectForKey:@"name"];
    NSString *desc = [dict objectForKey:@"description"];
    NSString *url = [dict objectForKey:@"url"];
    NSString *tag = [dict objectForKey:@"tag"];
    NSString *icon = [dict objectForKey:@"icon"];
    SBJsonWriter *writer = [[SBJsonWriter alloc]init];
    NSString *devices = [writer stringWithObject:[dict objectForKey:@"devices"]];
    NSString *imageSmall = [dict objectForKey:@"imageSmall"];
    NSString *imageMiddle = [dict objectForKey:@"imageMiddle"];
    NSString *imageLarge = [dict objectForKey:@"imageLarge"];
    NSString *author = [dict objectForKey:@"author"];
    NSString *authorUrl = [dict objectForKey:@"authorUrl"];
    NSString *teachUrl = [dict objectForKey:@"teachUrl"];
    
    if(_lastArticleTime > time.intValue){
        _lastArticleTime = time.intValue;
    };
    _lastArticleId = articleId.intValue;
    NSLog(@"lastArticleId:%d",_lastArticleId);
    NSArray *array = [[PGCoreDataManager sharedInstance]dataWithPredicateString:[NSString stringWithFormat:@"articleid == %d", articleId.intValue] entityName:@"Article" fetchLimit:1];
    if(array.count==0){
        PGArticle *article = (PGArticle*)[[PGCoreDataManager sharedInstance]createAndAddDataByEntityName:@"Article"];
        article.articleid = articleId;
        article.media = media;
        article.time = time;
        article.devices = devices;
        article.ispub = ispub;
        article.views = views;
        article.favors = favors;
        article.name = name;
        article.desc = desc;
        article.url = url;
        article.tag = tag;
        article.icon = icon;
        article.imageSmall = imageSmall;
        article.imageMiddle = imageMiddle;
        article.imageLarge = imageLarge;
        article.author = author;
        article.authorUrl = authorUrl;
        article.teachUrl = teachUrl;
    }else{
        PGArticle *article = (PGArticle*)[array objectAtIndex:0];
        article.articleid = articleId;
        article.media = media;
        article.time = time;
        article.ispub = ispub;
        article.views = views;
        article.favors = favors;
        article.name = name;
        article.devices = devices;
        article.desc = desc;
        article.url = url;
        article.tag = tag;
        article.icon = icon;
        article.imageSmall = imageSmall;
        article.imageMiddle = imageMiddle;
        article.imageLarge = imageLarge;
        article.author = author;
        article.authorUrl = authorUrl;
        article.teachUrl = teachUrl;
    }
}
-(PGArticle*)articleWithID:(int)articleId{
   NSArray*array = [[PGCoreDataManager sharedInstance]dataWithPredicateString:[NSString stringWithFormat:@"articleid == %d", articleId] entityName:@"Article" fetchLimit:1];
    if(array&&array.count>0){
        return [array objectAtIndex:0];
    }else{
        return nil;
    }
}
-(NSArray*)favors{
    NSArray*array = [[PGCoreDataManager sharedInstance]dataWithPredicateString:nil entityName:@"Favor" fetchLimit:0];
    return array;
}
-(BOOL)favorByArticleId:(int)articleId{
    NSArray*array = [[PGCoreDataManager sharedInstance]dataWithPredicateString:[NSString stringWithFormat:@"articleid == %d", articleId] entityName:@"Favor" fetchLimit:1];
    return array&&array.count>=1;
}
-(void)addFavor:(int)articleId{
    NSArray*array = [[PGCoreDataManager sharedInstance]dataWithPredicateString:[NSString stringWithFormat:@"articleid == %d", articleId] entityName:@"Favor" fetchLimit:1];
    if(array&&array.count>=1){
        
    }else{
        PGFavor *favor = (PGFavor*)[[PGCoreDataManager sharedInstance]createAndAddDataByEntityName:@"Favor"];
        favor.articleid = [NSNumber numberWithInt:articleId];
        PGArticle*article = [self articleWithID:articleId];
        favor.time = article.time;
        [[PGCoreDataManager sharedInstance]save];
    }
}
-(void)removeFavor:(int)articleId{
    NSArray*array = [[PGCoreDataManager sharedInstance]dataWithPredicateString:[NSString stringWithFormat:@"articleid == %d", articleId] entityName:@"Favor" fetchLimit:1];
    if(array&&array.count>=1){
        [[PGCoreDataManager sharedInstance]removeData:[array objectAtIndex:0]];
        [[PGCoreDataManager sharedInstance]save];
    }
}
+(PGArticleManager*)sharedManager{
    if(_instance==nil){
        _instance = [[PGArticleManager alloc]init];
    }
    return _instance;
}
@end
